package com.zf.museum.service.impl;


import com.zf.museum.bean.GetResult;
import com.zf.museum.bean.Msg;
import com.zf.museum.bean.Question;
import com.zf.museum.bean.Result;
import com.zf.museum.model.*;
import com.zf.museum.repository.*;
import com.zf.museum.service.MultiChoicesService;
import com.zf.museum.service.RecordService;
import com.zf.museum.service.WrongService;
import com.zf.museum.utils.ExcelUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;

@Service
public class MultiChoicesServiceImpl implements MultiChoicesService{

    @Autowired
    private MultiChoicesRepository multiChoicesRepository;
    @Autowired
    private WrongService wrongService;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private RecordService recordService;
    @Autowired
    private RecordRepository recordRepository;

    @Override
    public Result upload(MultipartFile file) {

        Result result = GetResult.fail();
        List<MultiChoices> multiChoices = new ArrayList<>();
        String fileName = file.getOriginalFilename();

        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
            result.setMsg("上传文件格式错误");
            return result;
        }

        boolean isExcel2003 = true;
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }

        InputStream is = null;
        Workbook wb = null;
        try {
            is = file.getInputStream();
            if (isExcel2003) {
                wb = new HSSFWorkbook(is);
            } else {
                wb = new XSSFWorkbook(is);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        Sheet sheet = wb.getSheetAt(0);
        if(sheet == null){
            result.setMsg("导入失败,上传文本为空");
            return result;
        }

        MultiChoices multiChoices1 = null;

        for (int r = 1; r <= sheet.getLastRowNum(); r++) {
            //每行
            Row row = sheet.getRow(r);
            //每个单元格
            Cell cell = null;
            if (row == null){
                continue;
            }
            /*提取题目内容*/
            cell = row.getCell(0);
            String content = ExcelUtil.getCellValue(cell);
            if(content == null || content.isEmpty()){
                result.setMsg("导入失败，第"+(r+1)+"行中题目内容为空");
                return result;
            }
            /*提取选项*/
            cell = row.getCell(1);
            String option1 = ExcelUtil.getCellValue(cell);
            if(option1==null || option1.isEmpty()){
                result.setMsg("导入失败，第"+(r+1)+"行中选项1为空");
                return result;
            }
            cell = row.getCell(2);
            String option2 = ExcelUtil.getCellValue(cell);
            if(option2==null || option2.isEmpty()){
                result.setMsg("导入失败，第"+(r+2)+"行中选项2为空");
                return result;
            }
            cell = row.getCell(3);
            String option3 = ExcelUtil.getCellValue(cell);
            if(option3==null || option3.isEmpty()){
                result.setMsg("导入失败，第"+(r+3)+"行中选项3为空");
                return result;
            }
            cell = row.getCell(4);
            String option4 = ExcelUtil.getCellValue(cell);
            if(option4==null || option4.isEmpty()){
                result.setMsg("导入失败，第"+(r+1)+"行中选项4为空");
                return result;
            }

            Set<Answer> answers = new HashSet<>();
            Answer answer = null;
            String answer1 = null;
            /*获取答案*/
            for (int i = 5; i < 9; i++) {
                cell = row.getCell(i);
                //判断单元格是否为空
                if (cell != null) {
                    cell = row.getCell(i);
                    answer1 = ExcelUtil.getCellValue(cell);
                    answer = new Answer();
                    answer.setContent(answer1);
                    answers.add(answer);
                }
            }

            multiChoices1 = new MultiChoices();
            multiChoices1.setAnswers(answers);
            multiChoices1.setContent(content);
            multiChoices1.setOption1(option1);
            multiChoices1.setOption2(option2);
            multiChoices1.setOption3(option3);
            multiChoices1.setOption4(option4);
            multiChoices.add(multiChoices1);
        }
        try {
            multiChoicesRepository.saveAll(multiChoices);
        } catch (Exception e) {
            e.printStackTrace();
            return result;
        }

        return GetResult.success();
    }

    @Override
    public List<MultiChoices> findAll() {
        return multiChoicesRepository.findAll();
    }

    @Override
    public Result update(List<MultiChoices> multiChoices) {

        try {
            multiChoicesRepository.saveAll(multiChoices);
        } catch (Exception e) {
            e.printStackTrace();
            return GetResult.fail();
        }
        return GetResult.success();
    }

    @Override
    @Transactional
    public Result delete(List<Long> ids) {

        try {
            for (Long id: ids
                 ) {
                multiChoicesRepository.deleteById(id);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return GetResult.fail();
        }

        return GetResult.success();
    }

    @Override
    public boolean judge(Question question) {

        /*用户openId*/
        String openId = question.getOpenId();
        /*根据题号获取题目*/
        MultiChoices multiChoice = multiChoicesRepository.getOne(question.getId());
        boolean b = true;
        Set<Answer> answers = multiChoice.getAnswers();
        for (String answer: question.getAnswers()) {
            boolean a = false;
            for (Answer answer1 : answers) {
                if (answer1.getContent().equals(answer)) {
                    a = true;
                    break;
                }
            }
            if (!a) {
                b = false;
                break;
            }
        }
        /*答题失败*/
        if (!b) {
            wrongService.addMulti(multiChoice, openId);
        } else {
            /*保存答对记录*/
            recordService.addMulti(multiChoice, openId);
        }

        return b;
    }

    @Override
    public List<MultiChoices> getMultiChoices(String openId) {

        User user = userRepository.getUserByOpenId(openId);
        List<MultiChoices> record = recordRepository.getMultiChoices(user);
        List<MultiChoices> all = multiChoicesRepository.findAll();
        List<MultiChoices> multiChoices = new ArrayList<>();
        int count = 0;
        int size = all.size();
        while(true) {
            /*随机获取*/
            Random random = new Random();
            int a = random.nextInt(size);
            MultiChoices multiChoice = all.get(a);
            if (!record.contains(a) && count < 6) {
                multiChoices.add(multiChoice);
                count++;
                if (count == 6) {
                    break;
                }
            }
        }
        return multiChoices;
    }
}
